import {create} from 'zustand'

interface TicketRecord {
    id: string
    upn: string
    time: string
    status: 'success' | 'failed'
}

interface TicketState {
    checkReservation: boolean
    ticketRecords: TicketRecord[]
    toggleReservationCheck: () => void
    addTicketRecord: (upn: string, status: 'success' | 'failed') => void
    scanQRCode: (qrData: string) => Promise<boolean>
}

export const useTicketStore = create<TicketState>((set, get) => ({
    checkReservation: true,
    ticketRecords: [
        {
            id: '1',
            upn: '************************',
            time: '2025-08-13 10:55',
            status: 'success'
        },
        {
            id: '2',
            upn: '************************',
            time: '2025-08-13 10:55',
            status: 'success'
        },
        {
            id: '3',
            upn: '************************',
            time: '2025-08-13 10:55',
            status: 'success'
        },
        {
            id: '4',
            upn: '************************',
            time: '2025-08-13 10:55',
            status: 'success'
        },
        {
            id: '5',
            upn: '************************',
            time: '2025-08-13 10:55',
            status: 'success'
        },
        {
            id: '6',
            upn: '************************',
            time: '2025-08-13 10:55',
            status: 'success'
        },
        {
            id: '7',
            upn: '************************',
            time: '2025-08-13 10:55',
            status: 'success'
        }
    ],

    toggleReservationCheck: () => {
        set((state) => ({checkReservation: !state.checkReservation}))
    },

    addTicketRecord: (upn: string, status: 'success' | 'failed') => {
        const newRecord: TicketRecord = {
            id: Date.now().toString(),
            upn: upn.replace(/./g, '*'),
            time: new Date().toLocaleString('zh-CN', {
                year: 'numeric',
                month: '2-digit',
                day: '2-digit',
                hour: '2-digit',
                minute: '2-digit'
            }),
            status
        }

        set((state) => ({
            ticketRecords: [newRecord, ...state.ticketRecords]
        }))
    },

    scanQRCode: async (qrData: string) => {
        // 模拟扫码验票逻辑
        const {addTicketRecord} = get()

        try {
            // 模拟验票API调用
            const isValid = qrData.length > 0

            if (isValid) {
                addTicketRecord(qrData, 'success')
                return true
            } else {
                addTicketRecord(qrData, 'failed')
                return false
            }
        } catch (error) {
            addTicketRecord(qrData, 'failed')
            return false
        }
    }
}))

